import axios from 'axios'
import { Loading } from 'element-ui';

const service = axios.create({
    baseURL: process.env.VUE_APP_BASE_API
})

var loading;
service.interceptors.request.use(
    config => {
        var token = localStorage.getItem('token');
        config.headers.common['token'] = token;
        
        loading = Loading.service({
            lock: true,
            text: '加载中...',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.5)'           
        })
        return config;      
    },
    err => {
        return Promise.reject(err)
    }
)

service.interceptors.response.use(
    res => {
        if(res.data.code === '40499'){ //token 为空
            location.href = '/';
        }else if(res.data.code === '40500'){//token 过期
            localStorage.removeItem('token');
            location.href = '/';
        }else if(res.data.code === '40501'){//登录校验失败
            location.href = '/';
        }else if(res.data.code === '40502'){//用户已禁用
            location.href = '/';
        }
        
        // else if(res.data.token) { //刷新token
        //     localStorage.setItem('token', res.data.token);
        // }
        if(loading){
            loading.close();
        }
        return res;
    },
    err => {

        if(err.response.status === 500){
            err.data = {};
            err.data.code = 400;
            err.data.message = '系统繁忙,请稍候在试';
        }
        if(loading){
            loading.close();
        }
        return Promise.reject(err)
    }
)

export default service;